<?php

class InstallController extends BController
{	
	public function init()
	{
		if( ! $this->module->install)
		{
			throw new CHttpException(404, Yii::t('backend','Chức năng cài đặt cho module <strong>{module}</strong> đã bị khóa.', array('{module}'=>Yii::t('user','Quản Trị Thành Viên'))));
		}
		parent::init();
	}
	
	public function actionIndex()
	{
		$model = new InstallForm;
		if(isset($_POST["InstallForm"]))
		{
			$model->attributes = $_POST["InstallForm"];
			$tablePrefix = Yii::app()->db->tablePrefix . $model->module_prefix;
			$sqlFileToExecute = $this->module->basePath."/data/user.sql";
			
			$sql = file_get_contents($sqlFileToExecute);
			$sql = str_replace('{tablePrefix}',$tablePrefix, $sql);
			$cmd = Yii::app()->db->createCommand($sql);
			$s = $cmd->execute();
			
			$this->render('sql_done', array('sql'=>$sql));
		} else {
			// render the form for user to input table prefix
			$this->render('index',array('model'=>$model));
		}
	}

	/* TODO */
	private function createWebSetting()
	{
		$settings = array(
			'User'=>array( // group
				'user-register-rule'=>'User Registration Rule', // key => value
			)
		);
	}
	
	private function createDefaultGroup()
	{
		$defaultGroups = array('Root Admin','Admin','Super Mod','Mod','Vip Member','Member','Validating','Banned');
		foreach ($defaultGroups as $groupName) {
			$group = new UserGroup;
			$group->name = $groupName;
			try {
				$group->save();
			} catch(CException $e) {}
		}
	}
	
	public function actionCreateAdmin()
	{
		$model=new CreateUserForm('create');

	    if(isset($_POST['CreateUserForm']))
	    {
	        $model->attributes=$_POST['CreateUserForm'];
	        if($model->validate())
	        {
				$user = new User;				
				$user->group_id = UserGroup::ROOT_ADMIN;
				$user->first_name = $model->first_name;
				$user->last_name = $model->last_name;
				$user->name = $model->name;
				$user->email = $model->email;
				$user->password = User::EncryptPassword($model->password);
				$user->join_date = time();
				
				if($user->save())
				{
					$this->createDefaultGroup();
					if($model->sendWelcomeEmail && ! $this->sendWelcomeEmail($model))
					{
						Yii::app()->user->setFlash('error',Yii::t('user','Cấu hình PHPMailer có sai sót, email chưa được gửi đến thành viên.'));
					}					
					$this->redirect(array('adminDone'));
				}
	        }
	    }
	    $this->render('create_admin',array('model'=>$model));
	}
	
	public function actionAdminDone()
	{
		$this->render('admin_done');
	}


	/**
	 * Update on May 27, 2012
	 *
	 * @var AR CreateUserForm model
	 **/
	private function sendWelcomeEmail($model)
	{
		$message = "Xin chao <strong>{$model->name}</strong>, <br /><br />
			Mot tai khoan thanh vien quan tri vua duoc tao ra cho ban tai trang web <strong>".Yii::app()->name."</strong><br />
			Day la thong tin dang nhap cua ban:<br />
			Ten dang nhap: {$model->email}<br />
			Mat khau: {$model->password}<br /><br />
			Luu y: Hay thay doi mat khau de dam bao su an toan cho tai khoan.<br />
			<a href='" . Yii::app()->controller->createAbsoluteUrl('/user/profile/changePassword') . "'>
			Nhan vao day de dang nhap va thay doi mat khau.
			</a>";
		
		$mail = NMailer::SetupSmtpMail();
		$mail->AddAddress($model->email, $model->name);
		$mail->Subject = Yii::t('user',"Tai khoan quan tri duoc khoi tao");
		$mail->Body = $message;
		try {
			return $mail->Send();
		} catch(Exception $e)
		{
			return false;
		}
	}
	
}